<template>
	<view class="content">
		<input v-model="host" type="text" placeholder="请输入端口" />
		<view class="tips">
			<p>注意：</p>
			<ul>
				<li>授权设备与被授权设备需在同一局域网内</li>
				<li>输入的端口需要和被授权的设备提示的端口一致</li>
			</ul>
		</view>
		<button type="primary" @click="handleSend">确认授权</button>
	</view>
</template>

<script>
const udpClient = uni.requireNativePlugin('udp-client');
export default {
	data() {
		return {
			host: '',
			initStatus: false
		};
	},
	onLoad() {
		udpClient.setIsDebug(true);
		// udpClient.setUseHex(true);
		udpClient.setByteSize(2048);
		// udpClient.init(10005, this.onSocketMsg, this.onSocketError);
	},
	onUnload() {
		// 释放 socket，释放端口
		udpClient.release();
	},
	methods: {
		handleSend() {
			if (!this.host) {
				uni.showToast({
					icon: 'none',
					title: '请输入端口'
				});
				return;
			}
			if (!this.initStatus) {
				udpClient.init(this.host, this.onSocketMsg, this.onSocketError);
				this.initStatus = true;
			}

			console.log(udpClient, this.host);
			udpClient.send({
				data: 'true',
				port: this.host,
				host: '255.255.255.255', // 可选，不传默认为广播 255.255.255.255
				useHex: true // 是否发送 hexString，默认 false
			});
		},

		onSocketMsg(resData) {
			// resData 的数据结构：{ host, port, data, hex }
			console.log('接收到消息: ' + resData);
		},
		onSocketError(errMsg) {
			console.error('socket 异常：' + errMsg);
		}
	}
};
</script>

<style lang="scss" scoped>
.content {
	width: 100vw;
	height: 100vh;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;

	input {
		width: 700rpx;
		height: 80rpx;
		line-height: 80rpx;
		border: 1rpx solid #333;
		padding: 0 20rpx;
		border-radius: 20rpx;
		box-sizing: border-box;
	}

	.tips {
		width: 700rpx;
		color: #ff0000;
		margin: 20rpx 0;
	}
	button {
		width: 700rpx;
	}
}
</style>
